from django.shortcuts import render

# Create your views here.

from rest_framework.generics import ListAPIView, CreateAPIView, DestroyAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework_extensions.cache.decorators import cache_response
from rest_framework_extensions.cache.mixins import CacheResponseMixin
from areas.models import Area, Address
from areas.serializers import AreaSerializer, AddressSerializer


class AreasView(ListAPIView, CacheResponseMixin):

    """
        返回省数据, 因为是返回全部的. 所以用的就是listAPIView
    """

    # queryset = Area.objects.filter(parent=None)
    serializer_class = AreaSerializer

    def get_queryset(self):
        """由于返回值有可能是带有数据的, 所有就要去重写get_queryset方法, 通过返回值, 查询到我们想要的数据"""
        # 这个获取的是传递进来的键值对, 通过用self.request的方式获取,
        pk = self.kwargs.get('pk', None)
        if not pk:
            pk = None
        return Area.objects.filter(parent_id=pk)


class AddressViewSet(CreateAPIView, ListAPIView, UpdateAPIView, DestroyAPIView):
    """保存用户的收货地址"""

    serializer_class = AddressSerializer
    queryset = Address.objects.filter(is_deleted=False)

    permissions = [IsAuthenticated]

    def delete(self, request, *args, **kwargs):
        # user = self.request.user  获取到的是user对象 不是address对象
        address = self.get_object()
        address.is_deleted = True
        address.save()
        return Response()

